package com.player.audio;

import java.io.IOException;

import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.ToggleButton;

public class OdiohPlayaActivity extends Activity {
    
	//MediaPlayer
	private MediaPlayer audioPlayer = null;
	
	//SeekBars
	private SeekBar volumeSeekBar = null;
	private SeekBar timeSeekBar = null;
	
	//Buttons
	private ToggleButton playPauseButton = null;
	private ImageButton nextButton = null;
	private ImageButton previousButton = null; 
	
	//TextViews
	private TextView currentTimeTextView;
	private TextView durationTextView;
	
	//EditText
	private EditText songTitleText = null;
	
	//Handler
	private Handler timeHandler = null;
	
	//Runnable
	private Runnable updateTimeTask = null;
	
	
	//AudioPlayer
	
	public MediaPlayer getAudioPlayer() {
		if(audioPlayer == null) {
			
			OdiohPlayaApplication application = (OdiohPlayaApplication) getApplication();
			audioPlayer = (OdiohMediaPlayer) application.getAudioPlayer();
			audioPlayer.setOnPreparedListener(new OnPreparedListener() {
				
				@Override
				public void onPrepared(MediaPlayer arg0) {
					getTimeHandler().removeCallbacks(getUpdateTimeTask());
					((OdiohMediaPlayer) audioPlayer).setCurrentSongPosition(0);
					getTimeSeekBar().setProgress(0); 
					getCurrentTimeTextView().setText("00:00");
					getTimeHandler().postDelayed(getUpdateTimeTask(), 0);
	 							
				}
			});
			
			audioPlayer.setOnCompletionListener(new OnCompletionListener() {
				
								public void onCompletion(MediaPlayer player) {
							
									getTimeHandler().removeCallbacks(getUpdateTimeTask());
									audioPlayer.reset();
									
								 	int currentTrack = ((OdiohMediaPlayer) audioPlayer).getCurrentTrack();
									if (currentTrack + 1 < ((OdiohMediaPlayer) audioPlayer).getSongPathList().size()) {
				
										
										((OdiohMediaPlayer) audioPlayer).setCurrentTrack(currentTrack + 1);
										
										((OdiohMediaPlayer) audioPlayer).setCurrentSongTitle(((OdiohMediaPlayer) audioPlayer).getSongTitleList().get(((OdiohMediaPlayer) audioPlayer).getCurrentTrack()));
										
				
										
										try {
											((OdiohMediaPlayer) audioPlayer).setDataSource(((OdiohMediaPlayer) audioPlayer).getSongPathList().get(
													currentTrack + 1));
											((OdiohMediaPlayer) audioPlayer).prepare();
											((OdiohMediaPlayer) audioPlayer).start();
											((OdiohMediaPlayer) audioPlayer).setCurrentSongPosition(0);
										} catch (IllegalArgumentException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (IllegalStateException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										} catch (IOException e) {
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
				
								}
					
							}
							);
		}
		
		return audioPlayer;
	}
	
	
	//SeekBars
	
	public SeekBar getVolumeSeekBar() {
    	if(volumeSeekBar == null) {
    		volumeSeekBar = (SeekBar) findViewById(R.id.volumeSeekBar);
    		volumeSeekBar.setProgress(50);
    		volumeSeekBar.setMax(100);
            getAudioPlayer().setVolume(0.5f, 0.5f);
            volumeSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
   			
	   			@Override
	   			public void onStopTrackingTouch(SeekBar arg0) {
	   				// TODO Auto-generated method stub
	   			}
	   			
	   			@Override
	   			public void onStartTrackingTouch(SeekBar arg0) {
	   				// TODO Auto-generated method stub
	   			}
   			
	   			@Override
	   			public void onProgressChanged(SeekBar arg0, int progress, boolean fromUser) {
	   				 getAudioPlayer().setVolume(((float)progress/100), ((float)progress/100));
	   			}
            });
    	}
		return volumeSeekBar;
	}
	
	
	public SeekBar getTimeSeekBar() {
    	if(timeSeekBar == null) {
    		timeSeekBar = (SeekBar) findViewById(R.id.timeSeekBar);
    		
    		timeSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
     			
     			@Override
     			public void onStopTrackingTouch(SeekBar arg0) {
     				
     				
     				
    
     				int seconds = ((OdiohMediaPlayer) getAudioPlayer()).getCurrentSongPosition();
    
     				getCurrentTimeTextView().setText(String.format("%02d:%02d", (seconds%3600)/60, (seconds%60)));
     				getTimeHandler().removeCallbacks(getUpdateTimeTask());
     				if(!getPlayPauseButton().isChecked()) {
     					getAudioPlayer().start();
     					getTimeHandler().postDelayed(getUpdateTimeTask(), 0);
     				}
     				
     				else {
     					getPlayPauseButton().setChecked(false);
     				}
     				
     				
     			}
     			
     			@Override
     			public void onStartTrackingTouch(SeekBar arg0) {
     				getAudioPlayer().pause();
     				 
     			}
     			
     			@Override
     			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
     				
     				if(fromUser) {
     					
     					((OdiohMediaPlayer) getAudioPlayer()).seekTo(progress*1000);
     					((OdiohMediaPlayer) getAudioPlayer()).setCurrentSongPosition(progress);
     				}
     				
     			}
     		});
    	}
		return timeSeekBar;
	}
	
	
	//Buttons 
	
	public ToggleButton getPlayPauseButton() {
		if(playPauseButton == null) {
			playPauseButton = (ToggleButton) findViewById(R.id.playPauseButton);
			
		     playPauseButton.setOnCheckedChangeListener(new OnCheckedChangeListener() {
		 			
		 			@Override
		 			public void onCheckedChanged(CompoundButton button, boolean isChecked) {
		 		 
		 				if(isChecked) {
		 					getAudioPlayer().pause();
		 					 
		 					getTimeHandler().removeCallbacks(getUpdateTimeTask());
		 				}
		 				
		 				else {
		 					
		 					((OdiohMediaPlayer) getAudioPlayer()).seekTo(((OdiohMediaPlayer) getAudioPlayer()).getCurrentSongPosition()*1000);
		 					((OdiohMediaPlayer) getAudioPlayer()).start();
		 						 
		 					getTimeHandler().postDelayed(getUpdateTimeTask(), 0);
		 				}
		 			}
		 	});
		}
		return playPauseButton;
	}
	
	
	public ImageButton getNextButton() {
		if(nextButton == null) {
			nextButton = (ImageButton) findViewById(R.id.nextButton);
			
			nextButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					((OdiohMediaPlayer) getAudioPlayer()).nextTrack();
				 
				}
				
			});
			
		}
		return nextButton;
	}

 
	public ImageButton getPreviousButton() {
		if(previousButton == null) {
			previousButton = (ImageButton) findViewById(R.id.previousButton);		 
			previousButton.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					((OdiohMediaPlayer) getAudioPlayer()).previousTrack();
				}
				
			});
		}
		return previousButton;
	}
	
	
	//TextViews
	
	public TextView getCurrentTimeTextView() {
		if(currentTimeTextView == null) {
			currentTimeTextView = (TextView) findViewById(R.id.currentTime);
		}
		return currentTimeTextView;
	}

	public TextView getDurationTextView() {
		if(durationTextView == null) {
			durationTextView = (TextView) findViewById(R.id.duration);
		}
		return durationTextView;
	}

	
	//EditText
		
	public EditText getSongTitleText() {
		if(songTitleText == null) {
			songTitleText = (EditText) findViewById(R.id.songTitle);
		}
		return songTitleText;
	}

	
	//Handler	
	
	public Handler getTimeHandler() {
		if(timeHandler == null) {
			timeHandler = new Handler();
		}
		return timeHandler;
	}
	
	
	//Runnable	
	
	public Runnable getUpdateTimeTask() {
		
		if(updateTimeTask == null) {
			updateTimeTask = new Runnable() {
		          public void run() {
		          	 
		          	  OdiohMediaPlayer audioPlayer = (OdiohMediaPlayer) getAudioPlayer();
		              SeekBar timeSeekBar = getTimeSeekBar();
		          	  
		              String songTitle = audioPlayer.getCurrentSongTitle();
		              
		              if(songTitle != null) {
		              	getSongTitleText().setText(songTitle);
		              }
		        
		              
		          	if(getAudioPlayer().isPlaying()) {
		          									
		          			int trackDuration = getAudioPlayer().getDuration();
		          			int seconds = trackDuration / 1000;
		          			getDurationTextView().setText(String.format("%02d:%02d", (seconds%3600)/60, (seconds%60)));
		          			seconds = audioPlayer.getCurrentSongPosition() + 1;
		          			timeSeekBar.setMax((int) Math.round((double)trackDuration/1000));
		          			timeSeekBar.setProgress(seconds);
		          			if(((OdiohMediaPlayer) getAudioPlayer()).getCurrentSongPosition() < timeSeekBar.getMax()) {
		          				getCurrentTimeTextView().setText(String.format("%02d:%02d", (seconds%3600)/60, (seconds%60)));
		          			}
		          			
		          			((OdiohMediaPlayer) getAudioPlayer()).setCurrentSongPosition(audioPlayer.getCurrentSongPosition()+1);
		          			
						}
		          	
		          	else {
		          			getTimeHandler().removeCallbacks(getUpdateTimeTask());
		          	}
		          	
		              getTimeHandler().postDelayed(this, 1000);  
		          }
		       };
		}
		
		return updateTimeTask;
		
	}
	
	/** Called when the activity is first created. */
	
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.player);
         
        getPlayPauseButton();
        getPreviousButton();
        getNextButton();
        getVolumeSeekBar();
        
    }
        
        
  
    @Override
	public void onResume() {
    	
    	super.onResume();
		    	
    	if(getAudioPlayer().isPlaying()) { 
    	
    		int trackDuration = ((OdiohMediaPlayer) getAudioPlayer()).getDuration();
    		int seconds = trackDuration / 1000;
    		getDurationTextView().setText(String.format("%02d:%02d", (seconds%3600)/60, (seconds%60)));
			seconds = ((OdiohMediaPlayer) getAudioPlayer()).getCurrentSongPosition();
			getTimeSeekBar().setMax((int) Math.round((double)trackDuration/1000));
			getTimeSeekBar().setProgress(seconds);
			getCurrentTimeTextView().setText(String.format("%02d:%02d", (seconds%3600)/60, (seconds%60)));
		}
	}

	 
}